package org.phantom.securityframework.web.mgt;

import org.apache.shiro.config.Ini;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.SubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.phantom.securityframework.api.AccountManager;
import org.phantom.securityframework.api.AccountManager.AuthStatus;
import org.phantom.securityframework.api.domain.Account;
import org.phantom.securityframework.api.factory.ManagerFactory;
import org.phantom.securityframework.api.factory.ShiroRealmFactory;

/**
 * 用两个方法演示创建Shiro扩展点
 * @see org.phantom.securityframework.web.SecurityManagerFactory
 * @author david
 *
 */
public class WebSecurityManager extends DefaultWebSecurityManager implements org.phantom.securityframework.api.SecurityManager{

	
	protected ManagerFactory managerFactory = null;
	/**
	 * 启用帐号
	 */
	@Override
	public void enable(Subject subject) throws Exception {
		Account account = (Account) subject;
		account.setStatus(AuthStatus.getIndex(AuthStatus.ACTIVATION));

		ManagerFactory factory = this.managerFactory;
		AccountManager accountManager = this.buildAccountManager(factory);
		if(accountManager==null){
			throw new Exception("accountManager is null");
		}
		accountManager.modify(account);
	}
	/**
	 * 禁用帐号
	 */
	@Override
	public void disable(Subject subject) throws Exception{
		Account account = (Account) subject;
		account.setStatus(AuthStatus.getIndex(AuthStatus.UNACTIVATION));
		ManagerFactory factory = this.managerFactory;
		AccountManager accountManager = this.buildAccountManager(factory);
		if(accountManager==null){
			throw new Exception("accountManager is null");
		}
		accountManager.modify(account);
	}
	@Override
	protected SubjectContext createSubjectContext() {
		return new WebSubjectContext();
	}
	@Override
	protected SubjectContext copy(SubjectContext subjectContext) {
		return subjectContext;
	}

	protected ManagerFactory buildManagerFactory(Ini ini){
		if(managerFactory==null)
			managerFactory = ShiroRealmFactory.getInstance(ini);
		return managerFactory;
	}
	protected AccountManager buildAccountManager(ManagerFactory factory) throws Exception{
		return (AccountManager) factory.getService(AccountManager.class);
	}
	@Override
	public ManagerFactory getManagerFactory(Ini ini){
		return this.buildManagerFactory(ini);
	}
}